package com.drojian.demo3.multimedia;

import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import com.drojian.demo.R;

import java.io.IOException;
import java.util.HashMap;

public class SoundPoolActivity extends AppCompatActivity implements View.OnClickListener {
    private Button sound1,sound2,sound3,sound4,sound5,sound6;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.part3_activity_sound_pool);
        initViews();
        try {
            initSP();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    private SoundPool mSoundPool = null;
    private HashMap<Integer, Integer> soundID = new HashMap<Integer, Integer>();
    private void initSP() throws IOException {
        //设置最多可容纳5个音频流，音频的品质为5
        mSoundPool = new SoundPool(5, AudioManager.STREAM_SYSTEM, 5);
        soundID.put(1, mSoundPool.load(this, R.raw.soundpool, 1));
        soundID.put(2 , mSoundPool.load(getAssets().openFd("music1.mp3") , 1));  //需要捕获IO异常
        soundID.put(3, mSoundPool.load(this, R.raw.soundpool, 1));
        soundID.put(4, mSoundPool.load(this, R.raw.sound3_call, 1));
        soundID.put(5, mSoundPool.load(this, R.raw.sound5_load, 1));
    }
    private void initViews() {
        sound1 =  findViewById(R.id.sound1);
        sound2 =  findViewById(R.id.sound2);
        sound3 =  findViewById(R.id.sound3);
        sound4 =  findViewById(R.id.sound4);
        sound5 =  findViewById(R.id.sound5);
        sound6 =  findViewById(R.id.sound6);
        sound1.setOnClickListener(this);
        sound2.setOnClickListener(this);
        sound3.setOnClickListener(this);
        sound4.setOnClickListener(this);
        sound5.setOnClickListener(this);
        sound6.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.sound1:
                mSoundPool.play(soundID.get(1), 1, 1, 1, 0, 1);
                break;
            case R.id.sound2:
                mSoundPool.play(soundID.get(2), 1, 1, 1, 0, 1);
                break;
            case R.id.sound3:
                mSoundPool.play(soundID.get(3), 1, 1, 1, 0, 2);
                break;
            case R.id.sound4:
                mSoundPool.play(soundID.get(4), 1, 1, 1, 0, 1);
                break;
            case R.id.sound5:
                mSoundPool.play(soundID.get(5), 1, 1, 1, 0, 1);
                break;
            case R.id.sound6:
                //回收SoundPool资源
                mSoundPool.release();
                break;
        }

    }

}